package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoComment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoCommentApi videoCommentApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private FriendApi friendApi;

    /**
     * 上传视频
     *
     * @param videoThumbnail 封面图片文件
     * @param videoFile      视频文件
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        //1、将视频上传到FastDFS,获取访问URL
        String filename = videoFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2、将封面图片上传到阿里云OSS，获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3、构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }

        //发送消息
        mqMessageService.sendLogMessage(UserHolder.getUserId(), "0301", "video", videoId);
    }

    //查询视频列表
    @Cacheable(
            value = "videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")
    //userid _ page_pagesize
    public PageResult queryVideoList(Integer page, Integer pagesize) {

        //1、查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if ((page - 1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                //5、调用API根据PID数组查询动态数据
                list = videoApi.findMovementsByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length, pagesize);
        }
        //4、如果redis数据不存在，分页查询视频数据
        if (list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);  //page=1 ?
        }
        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            String key = Constants.VIDEOS_LIKE_KEY+"-" + video.getId();
            String hashkey = Constants.VIDEOS_LIKE_HASHKEY+"-" + UserHolder.getUserId();

            String key1 = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
            String hashKey1 = Constants.FOCUS_USER_KEY + video.getUserId();
            UserInfo info = map.get(video.getUserId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                String value = (String) redisTemplate.opsForHash().get(key, hashkey);
                if (value != null) {
                    vo.setHasLiked(1);
                }
                String v = (String) redisTemplate.opsForHash().get(key1, hashKey1);
                if (v != null){
                    vo.setHasFocus(1);
                }
                vos.add(vo);
            }
        }

        return new PageResult(page, pagesize, 0l, vos);
    }

    /**
     * 视频点赞
     *
     * @param id
     * @return
     */
    public Integer videoLike(String id) {
        //1.查询redis判断该用户是否点赞
        String key = Constants.VIDEOS_LIKE_KEY+"-"  + id;
        String hashkey = Constants.VIDEOS_LIKE_HASHKEY+"-"  + UserHolder.getUserId();
        String value = (String) redisTemplate.opsForHash().get(key, hashkey);
        if (value != null) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //2.查询api获取点赞数
        Integer videoLikeCount = videoApi.videoLike(id);
        //3.将点赞标识存入redis
        redisTemplate.opsForHash().put(key, hashkey, "1");
        return videoLikeCount;
    }

    /**
     * 视频取消点赞
     *
     * @param id
     * @return
     */
    public Integer videoDislike(String id) {
        //1.查询redis判断该用户是否点赞
        String key = Constants.VIDEOS_LIKE_KEY+"-"  + id;
        String hashkey = Constants.VIDEOS_LIKE_HASHKEY+"-"  + UserHolder.getUserId();
        String value = (String) redisTemplate.opsForHash().get(key, hashkey);
        if (value == null) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //2.查询api获取点赞数
        Integer videoDislikeCount = videoApi.videoDislike(id);
        //3.将点赞标识从redis删除
        redisTemplate.opsForHash().delete(key, hashkey);
        return videoDislikeCount;
    }

    //发布评论
    public void savevideoComments(String movementId, String comment1) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();
        //2、构造Comment
        VideoComment videoComment = new VideoComment();
        videoComment.setVideoId(new ObjectId(movementId));
        videoComment.setCommentType(CommentType.COMMENT.getType());
        Map map = JSON.parseObject(comment1, Map.class);
        String comment = (String) map.get("comment");
        videoComment.setContent(comment);
        videoComment.setUserId(userId);
        videoComment.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        videoCommentApi.save(videoComment);
    }

    //分页查询评论列表
    public PageResult findvideoComments(String videoId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<VideoComment> list = videoCommentApi.findVideos(videoId, CommentType.COMMENT, page, pagesize);
        //2、判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (VideoComment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            //从redis查询此动态是否已被点赞
            //构造redis的key.......
            ObjectId id = comment.getId();
            Long userId = UserHolder.getUserId();
            String key = Constants.VIDEOS_LIKE_KEY+"_"+ comment.getVideoId();
            String hashKey = Constants.VIDEOS_LIKE_HASHKEY+"_" + userId;
            if (userInfo != null) {
                CommentVo vo = new CommentVo(
                        videoId,userInfo.getAvatar(),userInfo.getNickname(),comment.getContent(),
                        new SimpleDateFormat("yyyy-MM-dd").format(comment.getCreated()),
                        comment.getLikeCount(),0
                );
                //查询redis
                String value = (String) redisTemplate.opsForHash().get(key, hashKey);
                if (value != null) {
                    vo.setHasLiked(1);
                }
                vos.add(vo);
            }
        }
        //5、构造返回值
        return new PageResult(page, pagesize, 0l, vos);
    }


    /**
     * 评论点赞
     *
     * @param id
     * @return
     */
    public Integer videocommentLike(String id) {
        Long userId = UserHolder.getUserId();
        String key = Constants.VIDEOS_LIKE_KEY+"_" + id;
        String hashKey = Constants.VIDEOS_LIKE_HASHKEY+"_" + userId;
        //1.调用redis查询是否已点赞
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (value != null) {
            throw new BusinessException(ErrorResult.likeError());
        }
        Integer likeCount = videoCommentApi.findCommentsLike(id);
        //将点赞状态存入redis
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return likeCount;
    }

    /**
     * 取消评论点赞
     *
     * @param id
     * @return
     */
    public Integer videocommentDislike(String id) {
        String key = Constants.VIDEOS_LIKE_KEY+"_" + id;
        String hashKey = Constants.VIDEOS_LIKE_HASHKEY+"_" + UserHolder.getUserId();
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (value == null) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        redisTemplate.opsForHash().delete(key, hashKey);
        Integer likeCount = videoCommentApi.commentDislike(id);
        return likeCount;
    }

    // 关注用户
    public void userFocus(String uid) {
        Boolean aBoolean = userLikeApi.saveOrUpdate(UserHolder.getUserId(), Long.valueOf(uid), true);
        if (!aBoolean){
            throw new BusinessException(ErrorResult.error());
        }
        Boolean b = userLikeApi.findIsLike(UserHolder.getUserId(), Long.valueOf(uid));
        if (b){
            friendApi.save(Long.valueOf(uid),UserHolder.getUserId());
        }
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = Constants.FOCUS_USER_KEY + uid;
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (value != null){
            throw new BusinessException(ErrorResult.error());
        }
        redisTemplate.opsForHash().put(key, hashKey, "value");
    }

    // 取消关注
    public void userUnFocus(String uid) {
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = Constants.FOCUS_USER_KEY + uid;
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (value == null){
            throw new BusinessException(ErrorResult.error());
        }
        redisTemplate.opsForHash().delete(key,hashKey);
        userLikeApi.delete(uid,UserHolder.getUserId());
    }
}
